<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Document, Location, Warning, Tools, User, Timer, Check, ArrowLeft, Refresh } from '@element-plus/icons-vue'
import Map from '@arcgis/core/Map'
import MapView from '@arcgis/core/views/MapView'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer'
import gaodeLayer from '@/utils/GaoDeBaseLayer'

const router = useRouter()
const userStore = useUserStore()
const currentUser = userStore.userInfo.username

// 地图和图层
let view: __esri.MapView
let roadDamageLayer: __esri.FeatureLayer

// 道路损坏数据
const roadDamageList = ref([])
const loading = ref(true)
const selectedDamage = ref(null)

// 处理对话框
const processDialogVisible = ref(false)
const processForm = reactive({
  maintainMethod: '',
  remark: '',
  status: '已完成'
})

// 维护方法选项
const maintainMethodOptions = [
  { value: '沥青修补', label: '沥青修补' },
  { value: '混凝土修复', label: '混凝土修复' },
  { value: '路面重铺', label: '路面重铺' },
  { value: '裂缝灌缝', label: '裂缝灌缝' },
  { value: '井盖更换', label: '井盖更换' },
  { value: '标线重绘', label: '标线重绘' },
  { value: '其他', label: '其他' }
]

// 初始化地图
const initMap = async () => {
  // 创建地图实例
  const map = new Map({
    basemap: {
      baseLayers: [gaodeLayer],
    },
  })

  // 创建地图视图
  view = new MapView({
    container: 'maintainerMapView',
    map: map,
    center: [116.3912, 39.9073], // 北京市中心坐标
    zoom: 12,
    popup: {
      dockEnabled: true,
      dockOptions: {
        buttonEnabled: false,
        breakpoint: false,
      },
    },
  })

  // 创建道路损坏要素图层
  roadDamageLayer = new FeatureLayer({
    url: 'https://services7.arcgis.com/gcgG56UMRGbwuqfF/arcgis/rest/services/RoadDamageSegment/FeatureServer/0',
    outFields: ['*'],
    popupTemplate: {
      title: '{roadName}',
      content: [
        {
          type: 'fields',
          fieldInfos: [
            { fieldName: 'damageType', label: '损坏类型' },
            { fieldName: 'severityLevel', label: '严重程度' },
            { fieldName: 'reportTime', label: '报告时间' },
            { fieldName: 'status', label: '处理状态' },
            { fieldName: 'description', label: '描述' },
          ],
        },
      ],
    },
    renderer: {
      type: 'simple',
      symbol: {
        type: 'simple-line',
        color: [255, 0, 0, 0.8], // 红色
        width: 4,
        style: 'solid',
      },
    },
  })

  // 将图层添加到地图
  map.add(roadDamageLayer)

  // 加载道路损坏数据
  await loadRoadDamageData()
}

// 加载道路损坏数据
const loadRoadDamageData = async () => {
  loading.value = true
  try {
    // 查询分配给当前养护人员的道路损坏数据
    const query = roadDamageLayer.createQuery()
    query.where = `maintainer = '${currentUser}'` // 只查询分配给当前用户的数据
    query.outFields = ["*"]
    query.returnGeometry = false // 不返回地理要素

    const results = await roadDamageLayer.queryFeatures(query)

    // 转换为数组，只存储属性数据，不存储地理要素
    roadDamageList.value = results.features.map(feature => {
      return {
        id: feature.attributes.OBJECTID,
        ...feature.attributes
      }
    })

    loading.value = false
  } catch (error) {
    console.error('加载道路损坏数据失败', error)
    ElMessage.error('加载数据失败，请稍后重试')
    loading.value = false
  }
}

// 获取状态标签类型
const getStatusType = (status) => {
  switch (status) {
    case '待处理':
      return 'info'
    case '已分配':
      return 'warning'
    case '处理中':
      return 'warning'
    case '已完成':
      return 'success'
    default:
      return 'info'
  }
}

// 获取优先级标签类型
const getPriorityType = (priority) => {
  switch (priority) {
    case '高':
      return 'danger'
    case '中':
      return 'warning'
    case '低':
      return 'info'
    default:
      return 'info'
  }
}

// 查看详情
const viewDetail = async (row) => {
  selectedDamage.value = row

  // 查询该道路的地理要素
  try {
    // 确保地图视图已经准备就绪
    if (!view || !view.ready) {
      console.log('地图视图尚未准备就绪')
      return
    }

    const query = roadDamageLayer.createQuery()
    query.where = `OBJECTID = ${row.id}`
    query.outFields = ["*"]
    query.returnGeometry = true

    const result = await roadDamageLayer.queryFeatures(query)

    if (result.features.length > 0) {
      const geometry = result.features[0].geometry
      // 缩放到该道路
      if (geometry) {
        try {
          await view.when() // 等待视图完全加载
          view.goTo({
            target: geometry,
            zoom: 15
          })
        } catch (e) {
          console.error('缩放地图失败', e)
        }
      }
    }
  } catch (error) {
    console.error('查询道路地理要素失败', error)
  }
}

// 开始处理
const startProcess = (row) => {
  // 更新状态为处理中
  updateStatus(row, '处理中')
}

// 打开处理完成对话框
const openProcessDialog = (row) => {
  selectedDamage.value = row
  processForm.maintainMethod = ''
  processForm.remark = ''
  processForm.status = '已完成'
  processDialogVisible.value = true
}

// 更新状态
const updateStatus = async (row, status) => {
  try {
    // 更新要素
    const attributes = {
      OBJECTID: row.id,
      status: status
    }

    const result = await roadDamageLayer.applyEdits({
      updateFeatures: [{ attributes }]
    })

    if (result.updateFeatureResults.length > 0) {
      ElMessage.success(`状态已更新为"${status}"`)
      selectedDamage.status = status
      // 重新加载数据
      await loadRoadDamageData()
    } else {
      ElMessage.error('更新失败')
    }
  } catch (error) {
    console.error('更新状态失败', error)
    ElMessage.error('操作失败，请稍后重试')
  }
}

// 提交处理结果
const submitProcess = async () => {
  if (!processForm.maintainMethod) {
    ElMessage.warning('请选择维护方法')
    return
  }

  try {
    // 更新要素
    const attributes = {
      OBJECTID: selectedDamage.value.id,
      status: processForm.status,
      maintainMethod: processForm.maintainMethod,
      maintainTime: new Date().toLocaleString(),
      remark: processForm.remark
    }

    const result = await roadDamageLayer.applyEdits({
      updateFeatures: [{ attributes }]
    })

    if (result.updateFeatureResults.length > 0) {
      ElMessage.success('处理结果已提交')
      processDialogVisible.value = false
      selectedDamage.status = processForm.status
      // 重新加载数据
      await loadRoadDamageData()
    } else {
      ElMessage.error('提交失败')
    }
  } catch (error) {
    console.error('提交处理结果失败', error)
    ElMessage.error('操作失败，请稍后重试')
  }
}

// 返回养护页面
const goToMaintenance = () => {
  router.push('/maintenance')
}

onMounted(() => {
  initMap()
})
</script>

<template>
  <div class="maintainer-road-damage-container">
    <div class="page-header">
      <div class="header-left">
        <el-button @click="goToMaintenance" plain>
          <el-icon><arrow-left /></el-icon> 返回养护页面
        </el-button>
      </div>
      <div class="header-title">
        <h1>道路损坏处理</h1>
        <p>查看和处理分配给您的道路损坏任务</p>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="loadRoadDamageData">
          <el-icon><refresh /></el-icon> 刷新数据
        </el-button>
      </div>
    </div>

    <el-row :gutter="20" class="main-content">
      <!-- 左侧列表 -->
      <el-col :span="12">
        <el-card class="damage-list-card">
          <template #header>
            <div class="card-header">
              <el-icon><Document /></el-icon>
              <span>我的道路损坏任务</span>
            </div>
          </template>

          <el-empty v-if="roadDamageList.length === 0 && !loading" description="暂无分配给您的任务"></el-empty>

          <el-table
            :data="roadDamageList"
            style="width: 100%"
            v-loading="loading"
            @row-click="viewDetail"
            highlight-current-row
          >
            <el-table-column prop="roadName" label="道路名称" width="120" />
            <el-table-column prop="damageType" label="损坏类型" width="120" />
            <el-table-column prop="severityLevel" label="严重程度" width="100">
              <template #default="scope">
                <el-tag
                  :type="scope.row.severityLevel === '危险' ? 'danger' :
                         scope.row.severityLevel === '严重' ? 'warning' :
                         scope.row.severityLevel === '中等' ? 'info' : 'success'"
                  size="small"
                >
                  {{ scope.row.severityLevel }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.status)" size="small">
                  {{ scope.row.status }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180">
              <template #default="scope">
                <el-button
                  v-if="scope.row.status === '已分配'"
                  size="small"
                  type="primary"
                  plain
                  @click.stop="startProcess(scope.row)"
                >
                  开始处理
                </el-button>
                <el-button
                  v-if="scope.row.status === '处理中'"
                  size="small"
                  type="success"
                  plain
                  @click.stop="openProcessDialog(scope.row)"
                >
                  完成处理
                </el-button>
                <el-button
                  size="small"
                  type="info"
                  plain
                  @click.stop="viewDetail(scope.row)"
                >
                  详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>

      <!-- 右侧地图 -->
      <el-col :span="12">
        <el-card class="map-card">
          <template #header>
            <div class="card-header">
              <el-icon><Location /></el-icon>
              <span>损坏位置地图</span>
            </div>
          </template>

          <div id="maintainerMapView" class="map-container"></div>
        </el-card>

        <!-- 详情卡片 -->
        <el-card v-if="selectedDamage" class="detail-card">
          <template #header>
            <div class="card-header">
              <el-icon><Warning /></el-icon>
              <span>损坏详情</span>
            </div>
          </template>

          <div class="detail-content">
            <div class="detail-item">
              <span class="detail-label">道路名称:</span>
              <span class="detail-value">{{ selectedDamage.roadName }}</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">损坏类型:</span>
              <span class="detail-value">{{ selectedDamage.damageType }}</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">严重程度:</span>
              <span class="detail-value">
                <el-tag
                  :type="selectedDamage.severityLevel === '危险' ? 'danger' :
                         selectedDamage.severityLevel === '严重' ? 'warning' :
                         selectedDamage.severityLevel === '中等' ? 'info' : 'success'"
                  size="small"
                >
                  {{ selectedDamage.severityLevel }}
                </el-tag>
              </span>
            </div>
            <div class="detail-item">
              <span class="detail-label">优先级:</span>
              <span class="detail-value">
                <el-tag :type="getPriorityType(selectedDamage.priority)" size="small">
                  {{ selectedDamage.priority }}
                </el-tag>
              </span>
            </div>
            <div class="detail-item">
              <span class="detail-label">状态:</span>
              <span class="detail-value">
                <el-tag :type="getStatusType(selectedDamage.status)" size="small">
                  {{ selectedDamage.status }}
                </el-tag>
              </span>
            </div>
            <div class="detail-item">
              <span class="detail-label">报告人:</span>
              <span class="detail-value">{{ selectedDamage.reportUser }}</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">报告时间:</span>
              <span class="detail-value">{{ selectedDamage.reportTime }}</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">描述:</span>
              <span class="detail-value description">{{ selectedDamage.description }}</span>
            </div>
            <div class="detail-actions">
              <el-button
                v-if="selectedDamage.status === '已分配'"
                type="primary"
                @click="startProcess(selectedDamage)"
              >
                <el-icon><Tools /></el-icon> 开始处理
              </el-button>
              <el-button
                v-if="selectedDamage.status === '处理中'"
                type="success"
                @click="openProcessDialog(selectedDamage)"
              >
                <el-icon><Check /></el-icon> 完成处理
              </el-button>
              <div v-if="selectedDamage.status === '已完成'" class="status-message success">
                <el-icon><Check /></el-icon> 您已完成此道路的维护工作
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 处理完成对话框 -->
    <el-dialog
      v-model="processDialogVisible"
      title="完成道路损坏处理"
      width="500px"
    >
      <div v-if="selectedDamage" class="process-dialog-content">
        <div class="damage-info">
          <p><strong>道路名称:</strong> {{ selectedDamage.roadName }}</p>
          <p><strong>损坏类型:</strong> {{ selectedDamage.damageType }}</p>
          <p><strong>严重程度:</strong> {{ selectedDamage.severityLevel }}</p>
        </div>

        <el-form label-width="100px" class="process-form">
          <el-form-item label="维护方法:">
            <el-select v-model="processForm.maintainMethod" placeholder="请选择维护方法" style="width: 100%">
              <el-option
                v-for="item in maintainMethodOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="备注:">
            <el-input
              v-model="processForm.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入维护备注信息"
            ></el-input>
          </el-form-item>

          <el-form-item label="状态:">
            <el-radio-group v-model="processForm.status">
              <el-radio label="已完成">已完成</el-radio>
              <el-radio label="处理中">处理中(需要后续处理)</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="processDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitProcess">
            提交处理结果
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.maintainer-road-damage-container {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-title {
  text-align: center;
}

.header-title h1 {
  font-size: 24px;
  margin: 0;
  color: #303133;
}

.header-title p {
  font-size: 14px;
  margin: 5px 0 0 0;
  color: #606266;
}

.main-content {
  flex: 1;
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  font-weight: bold;
}

.card-header .el-icon {
  margin-right: 10px;
  font-size: 18px;
}

.damage-list-card {
  height: 100%;
  margin-bottom: 20px;
}

.map-card {
  height: 400px;
  margin-bottom: 20px;
}

.map-container {
  height: 400px;
  width: 100%;
}

.detail-card {
  margin-bottom: 20px;
}

.detail-content {
  padding: 10px;
}

.detail-item {
  margin-bottom: 10px;
  display: flex;
}

.detail-label {
  font-weight: bold;
  width: 100px;
  color: #606266;
}

.detail-value {
  flex: 1;
}

.detail-value.description {
  white-space: pre-wrap;
}

.detail-actions {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.status-message {
  padding: 10px 15px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.status-message.success {
  background-color: #f0f9eb;
  color: #67c23a;
}

.process-dialog-content {
  padding: 10px;
}

.damage-info {
  margin-bottom: 20px;
  padding: 10px;
  background-color: #f8f8f8;
  border-radius: 4px;
}

.damage-info p {
  margin: 5px 0;
}
</style>
